package com.xmh.utils;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;

@SuppressWarnings("unchecked")
@Component
public class RedisClient {

	private static final String dataMapPath = "K:\\EclipseWork2\\gitee\\Mode_SSM-master\\data2.txt";
	private static final String dateMapPath = "K:\\EclipseWork2\\gitee\\Mode_SSM-master\\date2.txt";
//	private static final String dataMapPath = new File("").getAbsolutePath() + "\\data.txt";
//	private static final String dateMapPath = new File("").getAbsolutePath() + "\\date.txt";

	private static Map<String, Object> dateMap = null;

	private static Map<String, Object> dataMap = null;

	static {
		dateMap = JSONObject.parseObject(FileUtil.getFileStr(dateMapPath), Map.class);
		if (dateMap == null) {
			dateMap = new HashMap<String, Object>();
		}

		dataMap = JSONObject.parseObject(FileUtil.getFileStr(dataMapPath), Map.class);
		if (dataMap == null) {
			dataMap = new HashMap<String, Object>();
		}
	}

	public static void set(String key, Object object, long time) {
		dataMap.put(key, object);
		dateMap.put(key, new Date(new Date().getTime() + time).getTime());

		FileUtil.outFile(JSONObject.toJSONString(dateMap), dateMapPath);
		FileUtil.outFile(JSONObject.toJSONString(dataMap), dataMapPath);
	}

	public static void remove(String key) {
		dataMap.remove(key);
		dateMap.remove(key);

		FileUtil.outFile(JSONObject.toJSONString(dateMap), dateMapPath);
		FileUtil.outFile(JSONObject.toJSONString(dataMap), dataMapPath);
	}

	public static Object get(String key) {
		return dataMap.get(key);
	}

	@Scheduled(cron = "0/5 * * * * ? ")
	public static void deleteAfterCheck() {
		Set<String> keySet = dateMap.keySet();

		List<String> list = new ArrayList<>(keySet);

		Iterator<String> iterator = list.iterator();

		Date now = new Date();
		while (iterator.hasNext()) {
			String key = (String) iterator.next();
			Date object = new Date((Long) dateMap.get(key));

			if (object.getTime() < now.getTime()) {
				dataMap.remove(key);
				dateMap.remove(key);
			}
		}
		FileUtil.outFile(JSONObject.toJSONString(dateMap), dateMapPath);
		FileUtil.outFile(JSONObject.toJSONString(dataMap), dataMapPath);
	}

}
